//
//  PageViewController.m
//  ActiveDeck
//
//  Created by Chiao-Wei Liu on 2011/2/10.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PageViewController.h"
#import "HttpRequest.h"
#import "GDataXMLNode.h"
#import "AD_Grade.h"
#import "AD_Page.h"
#import "AD_Slide.h"
#import "AD_Kiosk.h"
#import "AD_Image.h"
#import "AD_Layer.h"
#import "AD_Button.h"
#import "AD_ViewPort_Button_Link.h"
#import "AD_Video.h"
#import "AD_WebView.h"
#import <QuartzCore/QuartzCore.h>
#import "AD_ContainerOB.h"
#import "WBImage.h"


#define VIEW_INSERT_INDEX 2

UIAlertView *alertMSG;
CGPoint preTouchPoint;

@implementation PageViewController
@synthesize pageOB, userData, PID, SlideID, PageCount ,PresentName, Kiosk,LABTLinkSets,mp,Show, numberCorrect, numberIncorrect,feedbackVC, Bar_UpperContainer,containOB,Bar_Container,SlideIndex,SlideCount, Vw_AddNote,EditIndex,SavedImage, Vw_AddPhotoNote, isEditingNote, isForPDF,oldWidth,oldX,oldY, noteWarning, photoNoteWarning, canExportToPDF, canNavigateForwards, canNavigateBackwards, hOffset, vOffset;


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */

#pragma mark -
#pragma mark Use Camera
#define MAX_LENGTH 1000

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSUInteger newLength = (textView.text.length - range.length) + text.length;
    if(newLength <= MAX_LENGTH)
    {
        return YES;
    } else {
        NSUInteger emptySpace = MAX_LENGTH - (textView.text.length - range.length);
        textView.text = [[[textView.text substringToIndex:range.location] 
                          stringByAppendingString:[text substringToIndex:emptySpace]]
                         stringByAppendingString:[textView.text substringFromIndex:(range.location + range.length)]];
        return NO;
    }
}



#pragma mark -
#pragma mark Use Camera

-(void)UserCamera
{
    [_delegate setUpdateStatus:NO:self];
    [_delegate ShowCamera:self];
}

-(void)notifySlideChange{
    if(Vw_AddNote){
        [noteWarning setHidden:NO];
    }
    
    if(Vw_AddPhotoNote){
        [photoNoteWarning setHidden:NO];
    }
}

-(void)AddPhotoNote
{
    UITextView *Text_PhotoNote = (UITextView *)[Vw_AddPhotoNote viewWithTag:1];
    Text_PhotoNote.delegate = self;
    
    for(int i=0 ; i < [containOB.Array_Photo count];i++)
    {
        AD_PhotoNote *adPhotoNote = [containOB.Array_Photo objectAtIndex:i];
        
        if(adPhotoNote.SlideIndex == SlideIndex)
        {
            Text_PhotoNote.text = adPhotoNote.Txt_Note;
            
            break;
        }
    }
    EditIndex = SlideIndex;
    
    [self.view  addSubview:Vw_AddPhotoNote];
    [Text_PhotoNote becomeFirstResponder];
}

-(IBAction)SavePhotoNote
{
    UITextView *Txt_PhotoNote = (UITextView *)[Vw_AddPhotoNote viewWithTag:1];
    
    AD_PhotoNote *adPhotoNote = [AD_PhotoNote alloc];
    adPhotoNote.Txt_Note = Txt_PhotoNote.text;
    adPhotoNote.SlideIndex = EditIndex;
    adPhotoNote.Path_Image = [NSString stringWithFormat:@"ImageSlide%d", EditIndex];
    
    if([containOB.Array_Photo count] < 1 )
        [containOB.Array_Photo addObject:adPhotoNote];
    else
    {
        BOOL found = FALSE;
        for(int i= 0; i < [containOB.Array_Photo count]; i++)
        {
            if(((AD_Note *)[containOB.Array_Photo objectAtIndex:i]).SlideIndex == EditIndex)
            {
                [containOB.Array_Photo replaceObjectAtIndex:i withObject:adPhotoNote];
                found = TRUE;
                break;
            }
        }
        
        if(!found)
            [containOB.Array_Photo addObject:adPhotoNote];
    }
    
    [adPhotoNote release];
    
    if(SavedImage.image.size.height > SavedImage.image.size.width)
        [UIImagePNGRepresentation([SavedImage.image rotate:UIImageOrientationRight]) writeToFile:[NSString stringWithFormat:@"%@/ImageSlide%d", containOB.Path_Container,EditIndex] atomically:YES];
    else
        [UIImagePNGRepresentation(SavedImage.image) writeToFile:[NSString stringWithFormat:@"%@/ImageSlide%d", containOB.Path_Container,EditIndex] atomically:YES];
    
    [Bar_Container initWithContainOB:containOB
                          totalSlide:SlideCount];
    [Vw_AddPhotoNote removeFromSuperview];
    Bar_Container.Img_BG.image = [UIImage imageNamed:@"bg_container_down.png"];
    [self performSelectorInBackground:@selector(SaveIntoFile) withObject:nil];
    [_delegate setUpdateStatus:YES:self];
}

- (void)EditPhotoNote:(int)editIndex
{
    [_delegate setUpdateStatus:NO:self];
    [[NSBundle mainBundle] loadNibNamed:@"View_AddPhotoNote" owner:self options:nil];
    UITextView *Txt_Note = (UITextView *)[Vw_AddPhotoNote viewWithTag:1];
    
    for(int i=0 ; i < [containOB.Array_Photo count];i++)
    {
        AD_PhotoNote *adPhotoNote = [containOB.Array_Photo objectAtIndex:i];
        
        if(adPhotoNote.SlideIndex == editIndex)
        {
            Txt_Note.text = adPhotoNote.Txt_Note;           
            SavedImage.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",containOB.Path_Container,  adPhotoNote.Path_Image]]];
            
            break;
        }
    }
    
    EditIndex = editIndex;
    [self.view  addSubview:Vw_AddPhotoNote];
    [Txt_Note becomeFirstResponder];
}


#pragma mark -
#pragma mark Note Editing

-(IBAction)SaveNote
{
    UITextView *Txt_Note = (UITextView *)[Vw_AddNote viewWithTag:1];
    
    
    AD_Note *adNote = [AD_Note alloc];
    adNote.Txt_Note = Txt_Note.text;
    adNote.SlideIndex = EditIndex;
    
    if([containOB.Array_Note count] < 1)
    {
        [containOB.Array_Note addObject:adNote];
    }
    else
    {
        BOOL found = FALSE;
        for(int i=0 ; i < [containOB.Array_Note count];i++)
        {
            if(((AD_Note *)[containOB.Array_Note objectAtIndex:i]).SlideIndex == EditIndex)
            {
                [containOB.Array_Note replaceObjectAtIndex:i withObject:adNote];
                found = TRUE;
                break;
            }
        }
        
        if(!found)
            [containOB.Array_Note addObject:adNote];
        
    }
    
    [adNote release];
    
    [Bar_Container initWithContainOB:containOB
                          totalSlide:SlideCount];
    [Vw_AddNote removeFromSuperview];
    
    Bar_Container.Img_BG.image = [UIImage imageNamed:@"bg_container_down.png"];
    
    [self performSelectorInBackground:@selector(SaveIntoFile) withObject:nil];
    
    [_delegate setUpdateStatus:YES:self];
    
}

- (void)AddNote
{
    [_delegate setUpdateStatus:NO:self];
    [[NSBundle mainBundle] loadNibNamed:@"View_AddNote" owner:self options:nil];
    UITextView *Txt_Note = (UITextView *)[Vw_AddNote viewWithTag:1];
    Txt_Note.delegate = self;
    
    for(int i=0 ; i < [containOB.Array_Note count];i++)
    {
        AD_Note *adNote = [containOB.Array_Note objectAtIndex:i];
        
        if(adNote.SlideIndex == SlideIndex)
        {
            Txt_Note.text = adNote.Txt_Note;
            
            break;
        }
    }
    EditIndex = SlideIndex;
    
    [self.view  addSubview:Vw_AddNote];
    [Txt_Note becomeFirstResponder];
}

- (void)EditNote:(int)editIndex
{
    [_delegate setUpdateStatus:NO:self];
    [[NSBundle mainBundle] loadNibNamed:@"View_AddNote" owner:self options:nil];
    UITextView *Txt_Note = (UITextView *)[Vw_AddNote viewWithTag:1];
    
    for(int i=0 ; i < [containOB.Array_Note count];i++)
    {
        AD_Note *adNote = [containOB.Array_Note objectAtIndex:i];
        
        if(adNote.SlideIndex == editIndex)
        {
            Txt_Note.text = adNote.Txt_Note;            
            break;
        }
    }
    
    EditIndex = editIndex;
    [self.view  addSubview:Vw_AddNote];
    [Txt_Note becomeFirstResponder];
}


-(IBAction)RemoveAddNote
{
    [_delegate setUpdateStatus:YES:self];
    [Vw_AddNote removeFromSuperview];
    [Vw_AddPhotoNote removeFromSuperview];
}


#pragma mark -
#pragma mark Load & Initialize Container

- (void)ShowMoreContainer
{
    [UIView beginAnimations:@"MoreSuperBar" context:nil];
    [UIView setAnimationDuration:0.5];
    
    if(Bar_Container.frame.origin.y == 785)
    {
        Bar_UpperContainer.frame = CGRectMake(0, -80 , 768, 40);
        Bar_Container.frame = CGRectMake(0, 1000, 768, 232);
        
        Bar_Container.Img_BG.image = [UIImage imageNamed:@"bg_container_up.png"];
    }
    else if (Bar_Container.frame.origin.y >= 952)
    {
        Bar_UpperContainer.frame = CGRectMake(0, 20, 768, 40);
        Bar_Container.frame = CGRectMake(0, 785, 768, 232);
        
        if(Bar_Container.UI_NoteScroll.contentSize.width < 1)
            Bar_Container.Img_BG.image = [UIImage imageNamed:@"bg_container_directions.png"];
        else
            Bar_Container.Img_BG.image = [UIImage imageNamed:@"bg_container_down.png"];
    }
    
    [UIView commitAnimations];
}

- (void)MaxContainer
{
    [UIView beginAnimations:@"MaxSuperBar" context:nil];
    [UIView setAnimationDuration:0.5];
    
    Bar_UpperContainer.frame = CGRectMake(0, 20, 768, 40);
    Bar_Container.frame = CGRectMake(0, 785, 768, 232);
    
    if(Bar_Container.UI_NoteScroll.contentSize.width < 1)
        Bar_Container.Img_BG.image = [UIImage imageNamed:@"bg_container_directions.png"];
    else
        Bar_Container.Img_BG.image = [UIImage imageNamed:@"bg_container_down.png"];
    
    
    [UIView commitAnimations];
}




-(void)bringContainer
{
    Bar_UpperContainer = [[UpContainerView alloc]initWithFrame:CGRectMake(0, -80, 768, 40)];
    [Bar_UpperContainer set_delegate:self];
    Bar_UpperContainer.lb_SlideCount.text = [NSString stringWithFormat:@"Slide %d/%d", SlideIndex + 1, SlideCount];
    Bar_UpperContainer.lb_PresentationName.text = PresentName;
    
    Bar_UpperContainer.bt_Share.hidden = !canExportToPDF;
    Bar_UpperContainer.bt_Share.enabled = canExportToPDF;
    
    [self.view addSubview:Bar_UpperContainer];
    
    NSLog(@"totalSlideCount = %d" , SlideCount);
    
    Bar_Container = [[ContainerView alloc]initWithFrame:CGRectMake(0, 1000, 768, 232)];
    [Bar_Container initWithContainOB:containOB
                          totalSlide:SlideCount];
    [Bar_Container set_delegate:self];
    [self.view addSubview:Bar_Container];
}

-(void)showSuperBar
{
    
    if(!Kiosk.enabled)
    {
        Bar_Container.Img_BG.image = [UIImage imageNamed:@"bg_container_up.png"];
        
        // toolbar
        [UIView beginAnimations:@"superBar" context:nil];
        [UIView setAnimationDuration:0.5];
        
        //        if(Bar_UpperContainer.frame.origin.y < 0)
        //        {
        //            Bar_UpperContainer.frame = CGRectMake(0, 0 , 768, 40);
        //            Bar_Container.frame = CGRectMake(0, 932, 768, 232);
        //        }
        //        else
        //        {
        if(Bar_Container.frame.origin.y < 952)
        {
            Bar_Container.frame = CGRectMake(0, 952, 768, 232);
        }
        else
        {
            Bar_UpperContainer.frame = CGRectMake(0, -80 , 768, 40);
            Bar_Container.frame = CGRectMake(0, 1000, 768, 232);
        }
        // }
        
        [UIView commitAnimations];
        
        //[self leavePresent];
    }
}



- (void) moviePlayBackDidFinish:(NSNotification*)notification 
{    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
 	// Remove observer
    [[NSNotificationCenter 	defaultCenter] 
     removeObserver:self
     name:MPMoviePlayerPlaybackDidFinishNotification 
     object:nil];
    
    
    
	//[self dismissModalViewControllerAnimated:YES];	
}

- (void)AddLayer
{
    int j=0;
    
    
    for (AD_Layer* layOB in pageOB.mut_Arr_Layers)
    {
        NSArray *layerCondition = [layOB.Condition componentsSeparatedByString:@"="];
        
        if([layerCondition count] > 0)
        {
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
            NSLog(@"Condition:%@, Value:%@", [layerCondition objectAtIndex:0], [layerCondition objectAtIndex:2]);
            NSString *ACTIVEDECKSAVEKEY = [layerCondition objectAtIndex:0];
            NSString *keyValue = [prefs stringForKey:ACTIVEDECKSAVEKEY];
            
            if(![keyValue isEqualToString:[layerCondition objectAtIndex:2]])
                continue;
        }
        
        UIView *layView = [[UIView alloc]initWithFrame:CGRectMake(layOB.left, layOB.top, layOB.Width, layOB.Height)];
        
        [layView setTag:layOB.ID];
        NSLog(@"SlideID:%d, PageID:%d, LayerID:%d",SlideID, pageOB.pageID, layView.tag);
        
        
        if(!layOB.Enabled)
            layView.alpha = 0;
        
        if(layOB.AutoHide)
        {
            UIButton *removeButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [removeButton setTag:layOB.ID];
            [removeButton setFrame:CGRectMake(layOB.left, layOB.top, layOB.Width, layOB.Height)];
            [removeButton addTarget:self action:@selector(AutoHidePress:) forControlEvents:UIControlEventTouchUpInside];
            [layView addSubview:removeButton];
        }
        
        for (AD_Video *video in layOB.AD_VideoSets)
        {
            
            [[UIApplication sharedApplication] setStatusBarHidden:NO];
            
            NSLog(@"Video File:%@", video.mediaName);
            NSURL *movieURL = [NSURL fileURLWithPath:video.mediaName];
            
            mp =  [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
            
            if ([mp respondsToSelector:@selector(loadState)]) 
            {
                // Set movie player layout
                if(Kiosk.enabled)
                {
                    [mp setControlStyle:MPMovieControlStyleNone];
                    mp.repeatMode = MPMovieRepeatModeOne;
                }
                else
                    [mp setControlStyle:MPMovieControlStyleFullscreen];
                
                [mp setFullscreen:NO];
                
                // May help to reduce latency
                [mp prepareToPlay];
                
                [[mp view] setFrame:CGRectMake(video.left , video.top, video.width, video.height)];
                [layView addSubview:[mp view]];   
                
            }  
            
            // Register to receive a notification when the movie has finished playing. 
            [[NSNotificationCenter defaultCenter] addObserver:self 
                                                     selector:@selector(moviePlayBackDidFinish:) 
                                                         name:MPMoviePlayerPlaybackDidFinishNotification 
                                                       object:nil];    
        }
        
        
        for (AD_Image *img in layOB.AD_ImageSets)
        {
            UIImageView *layImgView = [[UIImageView alloc]initWithImage:[UIImage imageWithData:[NSData dataWithContentsOfFile:img.imagePath]]];
            layImgView.frame = CGRectMake(img.left, img.top, img.width, img.height);
            
            NSArray *condition = [img.Condition componentsSeparatedByString:@"=="];
            
            [layImgView setHidden:[self setCondition:condition]];       
            
            [layView addSubview:layImgView];
            [layImgView release];
        }
        
        int i=0;
        
        for (AD_Button *multiButton in layOB.AD_ButtonSets)
        {
            AD_ViewPort_Button_Link *LBLink = [AD_ViewPort_Button_Link alloc];
            LBLink.Index_VP = j;
            LBLink.Index_BT = i++;
            [LABTlinkSets addObject:LBLink];
            [LBLink release];
            
            UIImage *offImage = [UIImage imageWithData:[NSData dataWithContentsOfFile:multiButton.imageOff]];
            UIImage *onImage = [UIImage imageWithData:[NSData dataWithContentsOfFile:multiButton.imageOn]];
            CGRect buttonFrame = CGRectMake(multiButton.left, multiButton.top, multiButton.width, multiButton.height);
            NSArray *condition = [multiButton.Condition componentsSeparatedByString:@"=="];
            
            UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [newButton setFrame:buttonFrame];
            [newButton setTag:[LABTlinkSets count]];
            [newButton setBackgroundImage:offImage forState:UIControlStateNormal];
            [newButton setBackgroundImage:onImage forState:UIControlStateHighlighted];
            [newButton setBackgroundImage:onImage forState:UIControlStateSelected];
            [newButton addTarget:self action:@selector(layButtonPress:) forControlEvents:UIControlEventTouchUpInside];
            
            [newButton setHidden:[self setCondition:condition]];            
            [layView addSubview:newButton];
        }
        
        //[DynamicLayers addObject:layView];            
        
        [self.view addSubview:layView];
        [layView release];
        
        j++;
    }
}

-(BOOL)setCondition:(NSArray *)condition{
    if([condition count] > 0)
    {
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        NSLog(@"Condition:%@, Value:%@", [condition objectAtIndex:0], [condition objectAtIndex:1]);
        NSString *ACTIVEDECKSAVEKEY = [condition objectAtIndex:0];
        NSString *keyValue = [prefs stringForKey:ACTIVEDECKSAVEKEY];
        
        return ![keyValue isEqualToString:[condition objectAtIndex:1]];        
    }
    
    return NO;
}

-(void)AutoHidePress:(id)sender
{
    UIButton *pressButton = (UIButton*)sender;
    NSLog(@"SlideID:%d, PageID:%d, LayerID:%d",SlideID, pageOB.pageID, pressButton.tag);
    
    UIView *removeView = [self.view viewWithTag:pressButton.tag];
    
    [self SetLayerAlpha:0
                setView:removeView];
}

-(void)SetLayerAlpha:(int)alphaValue
             setView:(UIView*)setView
{
    [UIView beginAnimations:@"superBar" context:nil];
    [UIView setAnimationDuration:0.5];
    setView.alpha = alphaValue;
    [UIView commitAnimations];
}

-(void)layButtonPress:(id)sender
{
    UIButton *pressButton = (UIButton *)sender;
    NSLog(@"ButtonLog%d", pressButton.tag);
    AD_ViewPort_Button_Link * LALink = (AD_ViewPort_Button_Link*)[LABTlinkSets objectAtIndex:pressButton.tag - 1];
    NSLog(@"Press Button Index %d, Layer Index %d", LALink.Index_BT, LALink.Index_VP);
    
	AD_Button *multiButton = (AD_Button*)[[(AD_Layer*)[pageOB.mut_Arr_Layers objectAtIndex:LALink.Index_VP] AD_ButtonSets] objectAtIndex:LALink.Index_BT];
    
    [self buttonAction:multiButton];
}

-(void)buttonAction:(AD_Button*)multiButton
{
    //NSLog(@"Button Type %@", multiButton.buttonType);
    if(Kiosk.enabled){
        [self userActivate];
    }   
    
    for(AD_Action *action in multiButton.actions){
        if([action isKindOfClass:[Action_Next class]]){
            NSLog(@"Go to the next page");
            [self loadNextPage];
        }else if ([action isKindOfClass:[Action_GoTo class]]) {
            Action_GoTo* gt = (Action_GoTo*)action;
            NSLog(@"Go To Special Session");
            
            vOffset = gt.vOffset;
            hOffset = gt.hOffset;
            
            [self GoToSection:gt.section
                    NewPageID:gt.page];
            
        }else if ([action isKindOfClass:[Action_Layer class]]){
            Action_Layer* layer = (Action_Layer*)action;
            NSLog(@"Layer Button Pressed");
            NSLog(@"Target LayerID:%d", layer.TargetID);            
            
            UIView *viewLayer = [self.view viewWithTag:layer.TargetID];
            
            if([layer.state isEqualToString:@"On"]){
                
                [self SetLayerAlpha:100 setView:viewLayer];
                [self enableOtherButtons:layer :NO];                
                
            }
            else if([layer.state isEqualToString:@"Off"]){                
                [self SetLayerAlpha:0 setView:viewLayer];
                [self enableOtherButtons:layer :YES];
            }
            else
            {
                if(viewLayer.alpha == 0){
                    [self SetLayerAlpha:100 setView:viewLayer];
                    [self enableOtherButtons:layer :NO];
                }
                else{
                    [self enableOtherButtons:layer :YES];
                    [self SetLayerAlpha:0 setView:viewLayer];
                }
            }
            
        } else if ([action isKindOfClass:[Action_Command class]]){
            Action_Command* command = (Action_Command*)action;
            
            [command execute:self];
        } else if ([action isKindOfClass:[Action_Back class]]){            
            [_delegate navigateBackwards];
        }
    }
    
    //    if ([multiButton.buttonType isEqualToString:@"Next"]) {
    //		NSLog(@"Go to the next page");
    //        [self loadNextPage];
    //	}else if ([multiButton.buttonType isEqualToString:@"GoTo"]) {
    //        NSLog(@"Go To Special Session");
    //        [self GoToSection:multiButton.section
    //                NewPageID:multiButton.page];
    //    }else if ([multiButton.buttonType isEqualToString:@"Layer"]){
    //        NSLog(@"Layer Button Pressed");
    //        NSLog(@"Target LayerID:%d", multiButton.TargetID);
    //        
    //        UIView *GanLayer = [self.view viewWithTag:multiButton.TargetID];
    //        if([multiButton.State isEqualToString:@"On"])
    //            [self SetLayerAlpha:100 setView:GanLayer];
    //        else if([multiButton.State isEqualToString:@"Off"])
    //            [self SetLayerAlpha:0 setView:GanLayer];
    //        else
    //        {
    //            if(GanLayer.alpha == 0)
    //                [self SetLayerAlpha:100 setView:GanLayer];
    //            else
    //                [self SetLayerAlpha:0 setView:GanLayer];
    //        }
    //    }
}

-(void)enableOtherButtons:(Action_Layer *)layer :(BOOL)enable
{
    for (AD_Layer *l in [self.pageOB mut_Arr_Layers]) {
        if(l.ID != layer.TargetID){
            for (int i=0; i < [l.AD_ButtonSets count]; i++) {
                UIButton *button = (UIButton*)[[self.view viewWithTag:l.ID] viewWithTag:i+1];
                [button setEnabled:enable];
            }
        }
    }

}


#pragma mark -
#pragma mark Calling Delegate Function

-(id)delegate
{
	return _delegate;
}

-(void)setDelegate:(id)delegate
{
	_delegate = delegate;
}



-(void)GoToSection:(int)NewSectionID
         NewPageID:(int)NewPageID
{
    [mp pause];
    
    [_delegate LeaveSection:NewSectionID
                  NewPageID:NewPageID];
}

-(void)ResetIdleTimer
{
    [_delegate idleReset];
}


- (void)SaveIntoFile
{
    [_delegate SaveIntoFile];
}

//- (UIResponder *)nextResponder {
//    if(Kiosk.enabled)
//        [self userActivate];
//    return [super nextResponder];
//}

-(void) loadPrePage{
    int currentIndex = [[pageOB.parentSlide.PageIdLookup objectForKey:[NSNumber numberWithInt:pageOB.pageID]] intValue];
    
	if(currentIndex - 1 < 0)
		return;
	[_delegate changePage:currentIndex - 1 direction:UIViewAnimationDirectionReverse];
}

-(void) loadNextPage{
    //Get the index of the current page
    int currentIndex = [[pageOB.parentSlide.PageIdLookup objectForKey:[NSNumber numberWithInt:pageOB.pageID]] intValue];
    
	if(currentIndex + 1 > PageCount)
		return;
	[_delegate changePage:currentIndex + 1 direction:UIViewAnimationDirectionForward]; //LoadNext Page Array start 0 , so there is no needed to add extra 1
}

-(void)transitionWithView:(UIView *)firstView direction:(UIViewAnimationDirection)direction{
    [self transitionWithView:firstView direction:direction doTransition:YES];
}


-(void) transitionWithView:(UIView *)firstView 
                 direction:(UIViewAnimationDirection)direction
              doTransition:(BOOL)shouldAnimate{
    
    NSLog(@"Transition: %@ Direction: %d", pageOB.transition, direction);
    
    //Switch based on the transition
    if((pageOB.transition == nil) || [pageOB.transition isEqualToString:@"Cut"]){
        if(shouldAnimate){
            NSLog(@"No transition defined");
            if(self.view.superview == nil){
                [firstView addSubview:self.view];
            } else {
                [firstView bringSubviewToFront:self.view];
            }
        } else {
            [firstView insertSubview:self.view atIndex:VIEW_INSERT_INDEX];
        }
    } else if([pageOB.transition isEqualToString: @"Fade"]){
        if(shouldAnimate){
            [self.view setAlpha:0.0];
            if(self.view.superview == nil){
                [firstView addSubview:self.view];
                NSLog(@"Adding Subview: Fade");
            } else {
                [firstView bringSubviewToFront:self.view];
                NSLog(@"Bringing Subview to front: Fade");
            }
            
            //[firstView addSubview:self.view];
            
            [UIView animateWithDuration:1.0 
                             animations:^{ [self.view setAlpha:1.0]; }];
        } else {
            [firstView insertSubview:self.view atIndex:VIEW_INSERT_INDEX];
        }
        
    } else if([pageOB.transition isEqualToString: @"Curl"]){
        
        if(shouldAnimate){
            //Switch based on the direction (if necessary)
            if(direction == UIViewAnimationDirectionForward){
                [UIView transitionWithView:firstView duration:1.0
                                   options:UIViewAnimationOptionTransitionCurlUp
                                animations:^{ if(self.view.superview == nil){
                    [firstView addSubview:self.view];
                } else {
                    [firstView bringSubviewToFront:self.view];
                }
                                }
                                completion:NULL];
            } else {
                [UIView transitionWithView:firstView duration:1.0
                                   options:UIViewAnimationOptionTransitionCurlDown
                                animations:^{ if(self.view.superview == nil){
                    [firstView addSubview:self.view];
                } else {
                    [firstView bringSubviewToFront:self.view];
                }
                                }
                                completion:NULL];            
            }
        } else {
            [firstView insertSubview:self.view atIndex:VIEW_INSERT_INDEX];
        }
        
    } else if([pageOB.transition isEqualToString: @"Flip"]){
        
        if(shouldAnimate){
            //Switch based on the direction (if necessary)
            if(direction == UIViewAnimationDirectionForward){
                [UIView transitionWithView:firstView duration:1.0
                                   options:UIViewAnimationOptionTransitionFlipFromRight
                                animations:^{ if(self.view.superview == nil){
                    [firstView addSubview:self.view];
                } else {
                    [firstView bringSubviewToFront:self.view];
                }
                                }
                                completion:NULL];
            } else {
                [UIView transitionWithView:firstView duration:1.0
                                   options:UIViewAnimationOptionTransitionFlipFromLeft
                                animations:^{ if(self.view.superview == nil){
                    [firstView addSubview:self.view];
                } else {
                    [firstView bringSubviewToFront:self.view];
                }
                                }
                                completion:NULL];            
            }
        } else {
            [firstView insertSubview:self.view atIndex:VIEW_INSERT_INDEX];
        }
        
        
    } else if([pageOB.transition isEqualToString: @"Swipe"]){
        
        if(shouldAnimate){
            //Switch based on the direction (if necessary)
            if(direction == UIViewAnimationDirectionForward){
                [self.view setCenter:CGPointMake((384 + 768), 502)];
                //[firstView addSubview:self.view];
                if(self.view.superview == nil){
                    [firstView addSubview:self.view];
                } else {
                    [firstView bringSubviewToFront:self.view];
                }
                
                [UIView animateWithDuration:1.0 
                                 animations:^{ [self.view setCenter:CGPointMake(384, 502)];
                                     //[firstView setCenter:CGPointMake(firstView.center.x - 768, firstView.center.y)];
                                 }];
                
            } else {
                [self.view setCenter:CGPointMake((384 - 768), 502)];
                //[firstView addSubview:self.view];
                if(self.view.superview == nil){
                    [firstView addSubview:self.view];
                } else {
                    [firstView bringSubviewToFront:self.view];
                }
                
                [UIView animateWithDuration:1.0 
                                 animations:^{ [self.view setCenter:CGPointMake(384, 502)];
                                     //[firstView setCenter:CGPointMake(firstView.center.x + 768, firstView.center.y)];
                                 }];       
            }
        } else {
            [firstView insertSubview:self.view atIndex:VIEW_INSERT_INDEX];
        }
        
        
    }
}

-(void ) leavePresent
{
    [_delegate leavePresentation];
}

-(void) exportPDF
{
    if (Bar_Container.frame.origin.y == 785){
        [self ShowMoreContainer];
    }
    
    [_delegate exportPDF];
}


-(void) disMiss{
	[self.view removeFromSuperview];
    
}


-(void) submitUserData
{
    NSString *SubmitPath = [NSString stringWithFormat:@"%@/Config.svc/Submit", [HttpRequest GetSvcURL]];
    
	GDataXMLDocument *document = [[[GDataXMLDocument alloc] initWithRootElement:userData] autorelease];
	NSData	*xData = document.XMLData;
    NSString *submitData = [[NSString alloc] initWithData:xData encoding:NSUTF8StringEncoding];
	HttpRequest *submitRequest = [[HttpRequest alloc] init];
	NSString *result = [submitRequest XML_PostRequest:submitData urlString:[NSString stringWithFormat:@"%@/%d/%d", SubmitPath , PID,SlideID]];
	
    [submitData release];
    [submitRequest release];
    
    [_delegate updateSubmitStatus];
    
	alertMSG = [UIAlertView alloc];
	
	if([result isEqualToString:@"Error"])
	{
		alertMSG = [alertMSG initWithTitle:@"Error!"
								   message:@"There was a problem with your submission."
								  delegate:self 
						 cancelButtonTitle:@"Please seek assistance." 
						 otherButtonTitles:nil];
		
		[alertMSG show];
	}
	else {
        if(pageOB.grade.hasInstantFeedback){
            [self addInstantFeedback];
        } else {
            
            alertMSG = [alertMSG initWithTitle:@"Thanks!"
                                       message:nil
                                      delegate:self
                             cancelButtonTitle:nil 
                             otherButtonTitles:nil];
            [alertMSG show];
            
            [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(ReturnToHomePage) userInfo:nil repeats:NO];
        }
	}
    
    if(!pageOB.grade.hasInstantFeedback){
        [self GoToSection:0 NewPageID:0];
    }
}

- (void) addInstantFeedback{
    int currentIndex = [[pageOB.parentSlide.PageIdLookup objectForKey:[NSNumber numberWithInt:pageOB.pageID]] intValue];
    
    //Instant Feedback goes here.
    feedbackVC = [InstantFeedbackController alloc];
    if (currentIndex + 1 >= PageCount) {
        feedbackVC.hasNextPage = NO;
    } else {
        feedbackVC.hasNextPage = YES;
    }
    
    [feedbackVC setDelegate:self];    
    
    GDataXMLDocument *document = [[[GDataXMLDocument alloc] initWithRootElement:userData] autorelease];
    NSArray *answers = [[document rootElement] elementsForName:@"Answer"];
    
    if([pageOB.pageType isEqualToString:@"MultipleChoiceQuestion"] || [pageOB.pageType isEqualToString:@"ShortAnswerQuestion"]){
        
        for(GDataXMLElement *e in answers){
            if ( [[[e attributeForName:@"Page"] stringValue] isEqualToString:[NSString stringWithFormat:@"%d", pageOB.pageID]]) {
                NSString *answerAttr = @"Value";
                if ([[[e attributeForName:@"Type"] stringValue] isEqualToString:@"ShortAnswer"]) {
                    answerAttr = @"Text";
                }
                
                feedbackVC.submittedAnswer = [[e attributeForName:answerAttr] stringValue];
                if ([pageOB.pageType isEqualToString:@"MultipleChoiceQuestion"]) {
                    for (NSString *answerID in pageOB.grade.PossibleMultipleChoiceAnswers){
                        if([answerID isEqualToString:feedbackVC.submittedAnswer]){
                            pageOB.grade.question.submittedAnswerText = [pageOB.grade.PossibleMultipleChoiceAnswers objectForKey:answerID];
                        }
                    }
                    
                } else {
                    pageOB.grade.question.submittedAnswerText = feedbackVC.submittedAnswer;
                }
            }
        }
    } else if([pageOB.pageType isEqualToString:@"Categories"]){
        
        NSMutableDictionary *submittedAnswers = [[NSMutableDictionary alloc] init];
        
        for(GDataXMLElement *e in answers){
            if([[[e attributeForName:@"Page"] stringValue] isEqualToString:[NSString stringWithFormat:@"%d", pageOB.pageID]]){
                for(GDataXMLElement *category in [e elementsForName:@"Category"]){
                    for(GDataXMLElement *word in [category elementsForName:@"Item"]){
                        [submittedAnswers setObject:[[category attributeForName:@"ID"] stringValue] forKey:[[word attributeForName:@"ID"] stringValue]];
                    }
                }
            }                    
        }
        
        feedbackVC.submittedWordCategories = submittedAnswers;
        pageOB.grade.question.submittedCategories = submittedAnswers;
        [submittedAnswers release];
    }
    
    feedbackVC.page = pageOB;
    feedbackVC.numberCorrect = numberCorrect;
    feedbackVC.numberIncorrect = numberIncorrect;
    
    
    [self.view addSubview:feedbackVC.view];
    
    
}

- (void) windowClosed{
    numberCorrect = feedbackVC.numberCorrect;
    numberIncorrect = feedbackVC.numberIncorrect;
    
    [_delegate updateCorrectAnswers:numberCorrect :numberIncorrect];
    [self GoToSection:0 NewPageID:0];
    
}

- (void) showNextPage {
    numberCorrect = feedbackVC.numberCorrect;
    numberIncorrect = feedbackVC.numberIncorrect;
    
    [_delegate updateCorrectAnswers:numberCorrect :numberIncorrect];
    
    [self loadNextPage];
}

-(void) ReturnToHomePage
{
	[alertMSG dismissWithClickedButtonIndex:0 animated:YES];
}

-(void) appendUserData:(GDataXMLElement *)userDataNode{
	[userData addChild:userDataNode];
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(Kiosk.enabled)
        [self userActivate];
    else
    {
        UITouch* touch = [touches anyObject];
        preTouchPoint = [touch locationInView:self.view];
    }
}

- (void)userActivate
{
    [self ResetIdleTimer];
    
    if(SlideID == Kiosk.attractSlide && pageOB.pageID == Kiosk.attractPage)
        [self GoToSection:Kiosk.userSlide NewPageID:Kiosk.userPage];
}

#define DETECT_RANGE 22

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    UITouch* touch = [touches anyObject];
    CGPoint afterTouchPoint = [touch locationInView:self.view];
    if(feedbackVC ==nil)
    {
        if (preTouchPoint.x > (afterTouchPoint.x - DETECT_RANGE) && preTouchPoint.x < (afterTouchPoint.x + DETECT_RANGE))
            if(preTouchPoint.y > (afterTouchPoint.y -DETECT_RANGE) && preTouchPoint.y < (afterTouchPoint.y + DETECT_RANGE))
                [self showSuperBar];
    }
}

#define IMAGEVIEW_WHITE_LINE_OFFSET_X 1
#define IMAGEVIEW_WHITE_LINE_OFFSET_Y 1
#define IMAGEVIEW_DESIGNER_OFFSET 20

- (void)addImage{
    for(AD_Image *imageOB in pageOB.mut_Arr_Images)
    {
        NSLog(@"x:%d, y:%d, Width:%d, Height:%d, ImagePath:%@", imageOB.left, imageOB.top, imageOB.width, imageOB.height, imageOB.imagePath);
        
        UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageWithData:[NSData dataWithContentsOfFile:imageOB.imagePath]]];
        
        UIScrollView *scrollV;
        
        if([pageOB.pageType isEqualToString:@"DesignerSlide"])
            scrollV = [[UIScrollView alloc] initWithFrame: CGRectMake(imageOB.left + IMAGEVIEW_WHITE_LINE_OFFSET_X, imageOB.top -IMAGEVIEW_DESIGNER_OFFSET + IMAGEVIEW_WHITE_LINE_OFFSET_Y, imageOB.width, imageOB.height + IMAGEVIEW_DESIGNER_OFFSET)];
        else
            scrollV = [[UIScrollView alloc] initWithFrame: CGRectMake(imageOB.left , imageOB.top , imageOB.width, imageOB.height)];
        
        scrollV.delegate = self;
        scrollV.backgroundColor = [UIColor clearColor];
        scrollV.contentSize = imageV.frame.size;
        scrollV.bounces = NO;
        
        
        if(imageOB.ZoomEnabled)
        {
            if((int)imageV.frame.size.width != imageOB.width || (int)imageV.frame.size.height != imageOB.height)
            {
                NSLog(@"x:%d, y:%d, Width:%d, Height:%d, ImagePath:%@ , sourceWidth:%f, sourceHeight:%f", imageOB.left, imageOB.top, imageOB.width, imageOB.height, imageOB.imagePath,imageV.frame.size.width, imageV.frame.size.height);
                
                scrollV.minimumZoomScale = scrollV.frame.size.width / imageV.frame.size.width;
                scrollV.maximumZoomScale = 2.0;
                scrollV.clipsToBounds = YES;
                scrollV.showsHorizontalScrollIndicator = NO;
                scrollV.showsVerticalScrollIndicator = NO;
                NSLog(@"Scroll FrameSize : %f, Image FrameSize : %f, minimim : %f", scrollV.frame.size.width , imageV.frame.size.width, scrollV.minimumZoomScale);
            }
        }
        
        NSArray *condition = [imageOB.Condition componentsSeparatedByString:@"=="];
        
        [imageV setHidden:[self setCondition:condition]];
        
        [scrollV addSubview:imageV];
        [self.view addSubview:scrollV];
        if (imageOB.ZoomEnabled) 
            [scrollV setZoomScale:scrollV.minimumZoomScale];;
        
        [imageV release];
        [scrollV release];
    }
}

- (CGRect)centeredFrameForScrollView:(UIScrollView *)scroll andUIView:(UIView *)rView {
	CGSize boundsSize = scroll.bounds.size;
    CGRect frameToCenter = rView.frame;
    
    // center horizontally
    if (frameToCenter.size.width < boundsSize.width) {
        frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
    }
    else {
        frameToCenter.origin.x = 0;
    }
    
    // center vertically
    if (frameToCenter.size.height < boundsSize.height) {
        frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
    }
    else {
        frameToCenter.origin.y = 0;
    }
	
	return frameToCenter;
}



#pragma mark -
#pragma mark UIScrollViewDelegate

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    
    UIImageView *imageV;
    
    if([scrollView.subviews count] >0)
    {
        double Resize;
        
        imageV = [scrollView.subviews objectAtIndex:0];
        
        Resize = imageV.frame.size.width / oldWidth;
        oldWidth = imageV.frame.size.width;
        
        imageV.frame = [self centeredFrameForScrollView:scrollView andUIView:imageV];
        
        for (int i= 1; i < [scrollView.subviews count]; i++)
        {
            UIButton *Bt_Image = [scrollView.subviews objectAtIndex:i];
            
            double newW = Bt_Image.frame.size.width  * Resize;
            double newH = Bt_Image.frame.size.height * Resize;
            double newX = (Bt_Image.frame.origin.x - oldX) * Resize;
            double newY = (Bt_Image.frame.origin.y - oldY) * Resize;
            
            
            if(imageV.frame.size.height < scrollView.bounds.size.height)
            {
                newY= newY + imageV.frame.origin.y;
            }
            else
                oldY = 0;
            
            if(imageV.frame.size.width < scrollView.bounds.size.width)
            {
                newX = newX + imageV.frame.origin.x;
            }
            else
                oldX = 0;
            
            @try {
                Bt_Image.frame = CGRectMake( newX,  newY , newW, newH);
            }
            @catch (NSException *exception) {
                NSLog(@"CALayer position contains NaN");
            }
        }
        
        oldY = imageV.frame.origin.y;
        oldX = imageV.frame.origin.x;
    }
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    
    if([scrollView.subviews count] >0)
        return [scrollView.subviews objectAtIndex:0];
    else
        return NULL;
}

- (void)viewDidLoad {
    if(pageOB.mut_Arr_Orientations){
        //        for(NSNumber *o in pageOB.mut_Arr_Orientations){
        //            
        //        }
        [[UIApplication sharedApplication] setStatusBarHidden:!pageOB.showStatusBar withAnimation:YES];
        self.view.autoresizesSubviews = YES;
        self.view.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
        if([pageOB.mut_Arr_Orientations containsObject:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft]]){
            
            
            [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft];
            CGAffineTransform rotation = CGAffineTransformMakeRotation(-M_PI_2);
            [self.view setTransform:rotation];
            
        } else if ([pageOB.mut_Arr_Orientations containsObject:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight]]){
            [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
            CGAffineTransform rotation = CGAffineTransformMakeRotation(M_PI_2);
            [self.view setTransform:rotation];
        }
        
        [self.view setBounds:CGRectMake(0, 0, 768, 1024)];
        [self.view setFrame:CGRectMake(0, 0, 768, 1024)];
        
        NSLog(@"Left: %d, Right: %d, Portrait: %d, UpsideDown: %d", UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight, UIInterfaceOrientationPortrait, UIInterfaceOrientationPortraitUpsideDown);
        
    }
    
    if(!Kiosk.enabled)
    {
        [self bringContainer];
    }
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.    
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}


- (void)dealloc {
    [feedbackVC release];
    [pageOB release];
    [mp stop];
    [mp release];
    [Bar_UpperContainer release];
    [Vw_AddNote release];
    [super dealloc];
}


@end
